package com.dlc.felear.xiaoensale.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.dlc.felear.xiaoensale.R;
import com.dlc.felear.xiaoensale.constant.Constant;
import com.dlc.felear.xiaoensale.customView.ConfirmDialog;
import com.dlc.felear.xiaoensale.customView.MultInputDialog;
import com.dlc.felear.xiaoensale.customView.SingleInputDialog;
import com.dlc.felear.xiaoensale.dao.LocalUserDao;
import com.dlc.felear.xiaoensale.dao.FoodCategotyDao;
import com.dlc.felear.xiaoensale.entity.LocalUser;
import com.dlc.felear.xiaoensale.entity.FoodCategoty;
import com.dlc.felear.xiaoensale.helper.JsonHelper;
import com.dlc.felear.xiaoensale.helper.OkHttpManager;
import com.dlc.felear.xiaoensale.utils.HttpApi;
import com.dlc.felear.xiaoensale.utils.JasyptUtil;
import com.dlc.felear.xiaoensale.utils.UuidUtil;
import com.itdlc.android.library.utils.APPDidUtil;
import com.zhy.http.okhttp.callback.StringCallback;

import org.apache.commons.lang3.StringEscapeUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;


public class MenuCatogeryAdapter extends BaseAdapter implements View.OnClickListener, MultInputDialog.MultiDialogCallback,
        ConfirmDialog.ConfirmDialogCallback, SingleInputDialog.SingleDialogCallback {

    private static final String TAG = "FoodCategotyAdapter";
    // 上下文
    private Activity context;
    // 数据
    private List<FoodCategoty> items;
    private int type = 0;
    private int code = 0;
    private ConfirmDialog confirmDialog;
    private String tempId;
    private FoodCategotyDao foodCategotyDao;
    private SingleInputDialog singleInputDialog;
    private LocalUserDao localUserDao;
    private MultInputDialog multInputDialog;

    public void setValue(int type, int code) {
        this.code = code;
        this.type = type;
    }

    public MenuCatogeryAdapter(Context context) {
        this.context = (Activity) context;
        items = new ArrayList<>();
        foodCategotyDao = new FoodCategotyDao(context);
        confirmDialog = new ConfirmDialog(context, this);
        multInputDialog = new MultInputDialog(context, this);
        singleInputDialog = new SingleInputDialog(context, this);
        localUserDao = new LocalUserDao(context);
        initDalg();
    }

    private void initDalg() {

    }

    public List<FoodCategoty> getData() {
        return items;
    }


    public void setItems(List<FoodCategoty> data) {
        if (data.isEmpty()) {
            notifyDataSetChanged();
            return;
        }
        items.clear();
        items.addAll(data);
        notifyDataSetChanged();
    }

    public void clearData() {
        items.clear();
        notifyDataSetChanged();
    }


    @Override
    public int getCount() {
        return items == null ? 0 : items.size();
    }

    @Override
    public FoodCategoty getItem(int position) {
        return items.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = View.inflate(context, R.layout.adapter_menu_cat_item, null);
            holder.tv_name = convertView.findViewById(R.id.tv_name);
            holder.tv1 = convertView.findViewById(R.id.tv_1);
            holder.tv2 = convertView.findViewById(R.id.tv_2);
            holder.tv3 = convertView.findViewById(R.id.tv_3);
            holder.tv4 = convertView.findViewById(R.id.tv_4);
            holder.tv5 = convertView.findViewById(R.id.tv_5);
            holder.tv1.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
            holder.tv2.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
            holder.tv3.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
            holder.tv4.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        if (type == 1) {
            holder.tv3.setText("选择");
        }
        holder.tv1.setTag(R.id.tv_1, position);
        holder.tv1.setOnClickListener(this);
        holder.tv2.setTag(R.id.tv_2, position);
        holder.tv2.setOnClickListener(this);
        holder.tv3.setTag(R.id.tv_3, position);
        holder.tv3.setOnClickListener(this);
        holder.tv4.setTag(R.id.tv_4, position);
        holder.tv4.setOnClickListener(this);
        holder.tv_name.setText(items.get(position).getName());
        setzCfs(holder.tv5, items.get(position).getCookingType());
        return convertView;
    }

    private void setzCfs(TextView tv, int type) {
        if (type == 1) {
            tv.setText("方式:炒");
        } else {
            tv.setText("方式:焖煮");
        }
    }

    @Override
    public void onClick(View v) {
        int p = (int) v.getTag(v.getId());
        FoodCategoty foodCategoty = items.get(p);
        tempId = foodCategoty.getId();
        switch (v.getId()) {
            case R.id.tv_1:
                createTemp(foodCategoty);
                break;
            case R.id.tv_2:
                if (type == 0) {
                    confirmDialog.showDialog("是否要更新", R.id.tv_2);
                }
                break;
            case R.id.tv_3:
                if (type == 0) {
                    confirmDialog.showDialog("确定上传分类", R.id.tv_3);
                } else {
                    returnmsg(foodCategoty);
                }
                break;
            case R.id.tv_4:
                multInputDialog.showDialog(foodCategoty.getId());
                FoodCategoty foodCategoty1 = foodCategotyDao.queryForId(foodCategoty.getId());
                if (foodCategoty1 != null) {
                    showParamerDialog(foodCategoty1);
                }
                break;
        }
    }

    private void showParamerDialog(FoodCategoty foodCategoty) {
        if (foodCategoty.getCookingType() == 1) {
            multInputDialog.setTips("a", "n", "x","--");
            multInputDialog.setHintMsg("输入参数", "输入参数", "输入参数","输入参数");
            String a = "0";
            String n = "0";
            String x = "0";
            if (!TextUtils.isEmpty(foodCategoty.getParam1())) {
                HashMap<String, Object> map = JsonHelper.parserJson(foodCategoty.getParam1(), HashMap.class);
                Log.e(TAG, "Map:" + JsonHelper.toJson(map));
                if (map.containsKey("a")) {
                    a = map.get("a").toString();
                }
                if (map.containsKey("n")) {
                    n = map.get("n").toString();
                }
                if (map.containsKey("x")) {
                    x = map.get("x").toString();
                }
            }
            multInputDialog.setHintMsg(a, n, x,"--");
        } else if (foodCategoty.getCookingType() == 2) {
            multInputDialog.setTips("a", "b", "c", "z");
            multInputDialog.setHintMsg("输入参数", "输入参数", "输入参数", "输入参数");
            String a = "0";
            String b = "0";
            String c = "0";
            String z = "0";
            if (!TextUtils.isEmpty(foodCategoty.getParam3())) {
                HashMap<String, Object> map = JsonHelper.parserJson(foodCategoty.getParam3(), HashMap.class);
                Log.e(TAG, "Map:" + JsonHelper.toJson(map));
                if (map.containsKey("v1")) {
                    a = map.get("v1").toString();
                }
                if (map.containsKey("v2")) {
                    b = map.get("v2").toString();
                }
                if (map.containsKey("v3")) {
                    c = map.get("v3").toString();
                }
                if (map.containsKey("v4")) {
                    z = map.get("v4").toString();
                }
            }
            multInputDialog.setHintMsg(a, b, c,z);
        }
    }

    @Override
    public void selectResult(int value, int id) {
        if (value == 1 ) {
            singleInputDialog.setEtInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
            singleInputDialog.setHintMsg("请输入管理员密码");
            singleInputDialog.setMiWen();
            singleInputDialog.setTips("密码");
            singleInputDialog.showDialog(id);
        }
    }

    @Override
    public void SingleDialogInputResult(String value, int id) {
        LocalUser localUser = localUserDao.queryForId(UuidUtil.getUuidByName(Constant.USER_NAME));
        if (localUser == null) {
            showToast("用户不存在，请联系管理员添加用户");
            return;
        }
        if (TextUtils.equals(localUser.getPwd(), value)) {
            if (R.id.tv_2 == id) {
                downloadCatogety();
            }else if(R.id.tv_3 == id){
                updateCatogety(foodCategotyDao.queryForId(tempId));
            }
        } else {
            showToast("密码不正确");
        }
    }

    @Override
    public void multDialogInputResult(String value1, String value2, String value3,String value4, String id) {
        Log.e(TAG, "value1=" + value1 + " value2=" + value2 + " value3=" + value3+ " value4=" + value4 + " id=" + id);
        try {
            FoodCategoty foodCategoty = foodCategotyDao.queryForId(id);
            saveDialogValue(foodCategoty, value1, value2, value3, value4);
        } catch (Exception e) {
            showToast("输入数据格式有误，请查证");
        }
    }

    private void saveDialogValue(FoodCategoty foodCategoty, String value1, String value2, String value3, String value4) {
        Map<String, String> map = new HashMap<>();
        if (foodCategoty.getCookingType() == 1) {
            map.put("a", value1);
            map.put("n", value2);
            map.put("x", value3);
            foodCategoty.setParam1(JsonHelper.toJson(map));
        } else if (foodCategoty.getCookingType() == 2) {
            map.put("v1", value1);
            map.put("v2", value2);
            map.put("v3", value3);
            map.put("v4", value4);
            foodCategoty.setParam3(JsonHelper.toJson(map));
        }
        foodCategotyDao.update(foodCategoty);
        showToast("保存成功");
        Log.e(TAG, "saveParam:" + JsonHelper.toJson(foodCategotyDao.queryForId(foodCategoty.getId())));
    }

    static class ViewHolder {
        TextView tv_name, tv1, tv2, tv3, tv4, tv5;
    }


    private void createTemp(FoodCategoty foodCategoty) {
        if ((foodCategoty.getCookingType() == 1 && TextUtils.isEmpty(foodCategoty.getParam1())) ||
                (foodCategoty.getCookingType() == 2 && TextUtils.isEmpty(foodCategoty.getParam3()))) {
            showToast("请先配置参数值");
            return;
        }
        boolean flag = true;
        try {
            if (foodCategoty.getCookingType() == 1) {
                String str = StringEscapeUtils.unescapeJava(foodCategoty.getParam1());
                HashMap<String, String> map1 = JsonHelper.parserJson(str, HashMap.class);
                for (String key : map1.keySet()) {
                    Log.e(TAG, "key1:" + key + " value1:" + map1.get(key));
                    float vv1 = Float.parseFloat(map1.get(key));
                    if (vv1 == 0) {
                        flag = false;
                        break;
                    }
                }
            } else {
                String str = StringEscapeUtils.unescapeJava(foodCategoty.getParam3());
                HashMap<String, String> map2 = JsonHelper.parserJson(str, HashMap.class);
                for (String key : map2.keySet()) {
                    Log.e(TAG, "key2:" + key + " value2:" + map2.get(key));
                    float vv2 = Float.parseFloat(map2.get(key));
                    if (vv2 == 0) {
                        flag = false;
                        break;
                    }
                }
            }
        } catch (Exception e) {
            flag = false;
        }
        if (!flag) {
            showToast("参数值为整数或者浮点数");
            return;
        }
    }

    private void showToast(String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }

    private void updateCatogety(FoodCategoty foodCategoty) {
        if(foodCategoty==null){
            return;
        }
        Map<String, Object> p = new HashMap<>();
        p.put("categoryId", foodCategoty.getId());
        p.put("deviceId", APPDidUtil.getAppDid());
        p.put("sign", JasyptUtil.getInstance().getSign(p));
        p.put("weight", foodCategoty.getWeight());
        p.put("param1", foodCategoty.getParam1());
        p.put("param2", foodCategoty.getParam2());
        p.put("param3", foodCategoty.getParam3());
        p.put("param4", foodCategoty.getParam4());
        Log.e(TAG, "length："+foodCategoty.getParam2().length());
        String url = HttpApi.URL_UPDATE_CAT;
        OkHttpManager.HttpPostJson(url, p, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                Log.e(TAG, "Exception:" + e.getMessage());
                showToast(e.getMessage());
            }

            @Override
            public void onResponse(String s, int i) {
                try {
                    Log.e(TAG, "respone:" + s);
                    HashMap<String, Object> map = JsonHelper.parserJson(s, HashMap.class);
                   if(map.containsKey("msg")){
                        showToast((String)map.get("msg"));
                   }
                } catch (Exception e) {
                    showToast("数据解析异常");
                }
            }
        });

    }
    private void downloadCatogety() {
        Log.e(TAG,"更新本地食材分类");
        Map<String, Object> p = new HashMap<>();
        p.put("categoryId", tempId);
        p.put("sign", JasyptUtil.getInstance().getSign(p));
        Log.e(TAG, "paramer" + JsonHelper.toJson(p));
        String url = HttpApi.URL_LIST_CAT_DETAIL;
        OkHttpManager.HttpPostJson(url, p, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                Log.e(TAG, "Exception:" + e.getMessage());
                showToast(e.getMessage());
            }
            @Override
            public void onResponse(String s, int i) {
                try {
                    Log.e(TAG, "respone:" + s);
                    HashMap<String, Object> map = JsonHelper.parserJson(s, HashMap.class);
                    Log.e(TAG, "onResponse:" + JsonHelper.toJson(map));
                    if (map.containsKey("data") && map.get("data") != null) {
                        FoodCategoty foodCategoty = JsonHelper.parserJson(map.get("data").toString()
                                , FoodCategoty.class);
                        Log.e(TAG, "foodCategoty:" + JsonHelper.toJson(foodCategoty));
                        foodCategotyDao.update(foodCategoty);
                        showToast("数据更新成功");
                    } else {
                        showToast("已经是最新数据");
                    }
                } catch (Exception e) {
                    showToast("数据解析异常");
                }
            }
        });
    }

    private void returnmsg(FoodCategoty foodCategoty) {
        Intent intent = new Intent();
        //把返回数据存入Intent
        intent.putExtra(Constant.OPERATOR_VALUE_1, foodCategoty.getName());
        intent.putExtra(Constant.OPERATOR_VALUE_2, foodCategoty.getId());
        //设置返回数据
        context.setResult(code, intent);
        //关闭Activity
        context.finish();
    }
}